import re

from application import app
from flask import request, redirect, g
from common.models.User import User
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager

@app.before_request
def before_request():
    path = request.path

    # 不用验证的url
    ignore_urls = app.config['IGNORE_URLS']
    ignore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    # 1 用正则匹配
    pattern = re.compile("%s" % "|".join(ignore_check_login_urls))
    if pattern.match(path):
        #
        return

    # 获取当前用户登录
    user_info = check_login()
    g.current = None
    if user_info:
        g.current_user = user_info


    # check_login()
    user_info = check_login()

    # 2 用正则匹配
    pattern = re.compile("%s" % "|".join(ignore_urls))
    if pattern.match(path):
        return

    # 取决于user_info 返回值False--->/user/login
    if not user_info:
        return redirect(UrlManager.buildUrl('/user/login'))
    return

# 判断用户是否已经登录
def check_login():
    cookies = request.cookies
    auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config["AUTH_COOKIE_NAME"] in cookies else None
    app.logger.info(auth_cookie)
    # 判断cookie 是否为空
    if auth_cookie is None:
        return False
    # 切割#
    # auth_info[0]:授权码
    # auth_info[1]:用户数据库uid
    auth_info = auth_cookie.split("#")
    print("auth_info===", auth_info)

    # 长度不为2
    if len(auth_info) != 2:
        return False

    try:
        # 在数据库中无法查找到uid
        user_info = User.query.filter_by(uid=auth_info[1]).first()
    except Exception:
        return False

    # user_info (cookie)为空
    if user_info is None:
        return False

    # 授权码与服务器生成的授权码不一致
    if auth_info[0] != UserService.geneAuthCode(user_info):
        return False

    # 返回正确
    return user_info

